#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <nice2d/scene.h>
#include <nice2d/application.h>
#include <nice2d/background.h>
#include <nice2d/components/imagemanager.h>
#include <nice2d/components/fontmanager.h>
#include <nice2d/components/defaultcamera.h>
#include <nice2d/components/scenecamera.h>
#include <nice2d/string.h>

IMPLEMENT_OBJECT(Scene, Node)

class SceneData
{
public:
    std::string sceneName;
    sf::RectangleShape backgroundBox;
    BackgroundPointer background;

    void updateBackground()
    {
        if (background)
            background->applyBackground(backgroundBox);
    }
};

Scene::Scene(const std::string &name):
    data(new SceneData())
{
    data->sceneName = name;
}

Scene::~Scene()
{
}

std::string Scene::getSceneName() const
{
    return data->sceneName;
}

void Scene::setSceneBox(const sf::FloatRect &box)
{
    data->backgroundBox.setPosition({box.left, box.top});
    data->backgroundBox.setSize({box.width, box.height});
    GET_COMPONENT(this,SceneCamera)->setGlobalArea(box);
    data->updateBackground();
}

sf::FloatRect Scene::getSceneBox() const
{
    return sf::FloatRect(data->backgroundBox.getPosition(), data->backgroundBox.getSize());
}

void Scene::setBackground(BackgroundPointer background)
{
    if (background) {
        data->background = background;
        data->updateBackground();
    }
}

std::shared_ptr<Text> Scene::createToastText()
{
    auto text = std::make_shared<Text>();
    text->setFont("./../data/font/FZYTK.TTF");
    text->setCharacterSize(24);
    text->setTextColor(sf::Color::White);
    text->setSize(120, 36);
    text->setBackgroundColor(sf::Color::Transparent);
    text->setHMode(HMode_Left);
    text->setPosition(18.0f, 18.0f);
    return text;
}

void Scene::initial()
{
    auto camera = ADD_COMPONENT(this, SceneCamera);
    camera->setScene(as<Scene>());
    camera->setGlobalArea(getSceneBox());
    onInitialed();
}

void Scene::exit()
{
    auto camera = GET_COMPONENT(Application::getInstance(), DefaultCamera);
    camera->apply();
    onExit();
}

void Scene::onExit()
{
}

void Scene::onUpdateNode(float deltaTime)
{
    onUpdateScene(deltaTime);
}

void Scene::onUpdateScene(float deltaTime)
{
}

void Scene::onDrawEntity(sf::RenderTarget &target, sf::RenderStates states) const
{
    target.draw(data->backgroundBox, states);
}

void Scene::onDrawScene(sf::RenderTarget &target, sf::RenderStates states)
{

}

void Scene::onInitialed()
{
}
